package com.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class CodePicServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	protected void service (HttpServletRequest request,HttpServletResponse response)throws ServletException,
	IOException
	{
		String chose="23456789abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ";
		Random rand=new Random();
		HttpSession session=request.getSession(true);
		response.setContentType("image/jpeg");
		response.addHeader("pragma", "NO-cache");
		response.addHeader("Cache-Control", "no-cache");
		response.addDateHeader("Expries", 0);
		int width=65,height=20;
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
		Graphics g=image.getGraphics();
		g.setColor(new Color(51,102,255));
		g.fillRect(0, 0, width, height);
		g.setColor(Color.black);
		g.drawRect(0, 0, width-1, height-1);
		for(int i=0;i<30;i++)
		{
			g.setColor(getRandColor(100,150));
			int x=rand.nextInt(width);
			int y=rand.nextInt(height);
			int x1=rand.nextInt(10);
			int y1=rand.nextInt(10);
			g.drawLine(x, y, x1, y1);
		}
		g.setFont(new Font("Times New Roman", Font.BOLD + Font.ITALIC, 16));
		g.setColor(Color.WHITE);
		String sRand="";
		for(int i=0 ;i<4;i++)
		{
			String ranChar=String.valueOf(chose.charAt(rand.nextInt(chose.length())));
			sRand+=ranChar;
			g.drawString(ranChar, 14*i+6, 15);
		}
		session.setAttribute("verifyCode", String.valueOf(sRand));
		g.dispose();
		ServletOutputStream outStream= response.getOutputStream();
		JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(outStream);
		encoder.encode(image);
		outStream.flush();
		outStream.close();
	}
	 private Color getRandColor(int beginColor, int endColor) {
		    Random random = new Random();
		    if (beginColor > 255) {
		      beginColor = 255;
		    }
		    if (endColor > 255) {
		      endColor = 255;
		    }
		    int r = beginColor + random.nextInt(endColor - beginColor);
		    int g = beginColor + random.nextInt(endColor - beginColor);
		    int b = beginColor + random.nextInt(endColor - beginColor);
		    return new Color(r, g, b);
		  }
}
